<?php

namespace App\Console\Commands\Fix;

use App\Console\BaseCommand;
use App\Consts\GlobalConst;
use App\Consts\GlobalRelationshipConst;
use App\Models\SysDynamic;
use App\Models\UserAttention;
use App\Models\UserFollowingRelationship;

/**
 * 关注关系修复脚本
 * Class RelationFixCommand
 * @package App\Console\Commands\Fix
 */
class RelationShipFixCommand extends BaseCommand
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'fix:relationship {action} {--ids=}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'fix user relationship';

    /**
     * 关注关系修复 - 大V粉丝迁移
     * @return int
     * @throws \Exception
     */
    public function moveFansV()
    {
        /**
         * [!] 注意：--2021.03.12 迁移场景：
         *  - 本次只迁移 听君精选(00K4RTVDJEHD53QA2S0909GM) 和 听君情报员(00K5M3DXLEAEXWOZ8AKPRRIT)
         *  - 迁移数据不大（<1000），一次性处理完毕，另外两个账号暂时无数据
         */
        //$idAry = ["00K4RTVDJEHD53QA2S0909GM","00K5M3DXLEAEXWOZ8AKPRRIT"];
        $idAry = $this->_getIds();
        $keyCount = count($idAry);
        // 数据量不大，直接一次性处理完
        foreach ($idAry as $key => $userId) {
            // 获取数据模型
            $fansList = UserFollowingRelationship::setTableNameByTableCount($userId)
                ->where('attention_status', GlobalRelationshipConst::ATTENTION_STATUS_FANS)
                ->get()
                ->toArray();
            $finish = count($fansList);
            foreach ($fansList as $index => $item) {
                // 查询关注关系
                $infoFans = UserFollowingRelationship::getModel($userId)
                    ->where('user_id', $userId)
                    ->where('follow_id', $item['follow_id'])
                    ->first();
                $infoAttention = UserFollowingRelationship::getModel($item['follow_id'])
                    ->where('user_id', $item['follow_id'])
                    ->where('follow_id', $userId)
                    ->first();
                if ($infoFans || $infoAttention) {
                    $warn = ' - [HAS_ONE] ';
                    // 如果是单条记录，直接删除
                    if (empty($infoFans) && $infoAttention) {
                        if ($infoAttention->attention_status == GlobalRelationshipConst::ATTENTION_STATUS_NULL) {
                            // 没关系，保留记录，跳过
                            $warn .= "skip by infoAttention[{$infoAttention->attention_status}] : uid - $userId - fid - {$item['follow_id']} .";
                        } else {
                            // 关注关系|粉丝关系|互关，直接跳过
                            $warn .= "delete by infoAttention[{$infoAttention->attention_status}] : uid - $userId - fid - {$item['follow_id']} .";
                            $infoAttention->delete();
                        }
                    }
                    if (empty($infoAttention) && $infoFans) {
                        if ($infoFans->attention_status == GlobalRelationshipConst::ATTENTION_STATUS_NULL) {
                            // 没关系，保留记录，跳过
                            $warn .= "skip by infoFans[{$infoFans->attention_status}] : uid - $userId - fid - {$item['follow_id']} .";
                        } else {
                            // 关注关系|粉丝关系|互关，直接跳过
                            $warn .= "delete by infoFans[{$infoFans->attention_status}] : uid - $userId - fid - {$item['follow_id']} .";
                            $infoFans->delete();
                        }
                    }
                    $this->warn($warn);
                    $this->logger($warn, false, 'script');
                }
                // 有关系则不处理
                $infoFans = UserFollowingRelationship::getModel($userId)
                    ->where('user_id', $userId)
                    ->where('follow_id', $item['follow_id'])
                    ->first();
                if ($infoFans) continue;
                // 插入粉丝关系
                $data = [
                    'user_id' => $userId,
                    'follow_id' => $item['follow_id'],
                    'attention_status' => GlobalRelationshipConst::ATTENTION_STATUS_FANS,
                    'weight' => $item['weight'],
                    'created_at' => $item['created_at'],
                    'updated_at' => $item['updated_at'],
                ];
                UserFollowingRelationship::getModel($data['user_id'])->create($data);
                // 插入关注关系
                $data['user_id'] = $item['follow_id'];
                $data['follow_id'] = $userId;
                $data['attention_status'] = GlobalRelationshipConst::ATTENTION_STATUS_ATTENTION;
                $res = UserFollowingRelationship::getModel($data['user_id'])->create($data);
                if ($res) {
                    $uid = UserFollowingRelationship::getTableId($userId);
                    $fid = UserFollowingRelationship::getTableId($item['follow_id']);
                    $info = "[$index/$finish][".($key+1)."/$keyCount] insert data to `user_following_relationship_[$uid|$fid]` - " . json_encode($data);
                } else {
                    $info = "[$index/$finish][".($key+1)."/$keyCount] insert failed : id - {$item['id']} uid - $userId - fid - " . $item['follow_id'];
                }
                // log info
                $this->logger($info, true, 'script');
            }
        }
        return 1;
    }

    /**
     * 关注关系修复 - 同步大V动态到粉丝关注列表
     * @return int
     * @throws \Exception
     */
    public function syncAttentionV()
    {
        /**
         * [!] 注意：--2021.03.12 迁移场景：
         *  - 本次只同步 听君精选(00K4RTVDJEHD53QA2S0909GM) 动态
         *  - 同步数据不大（<2000），一次性处理完毕，另外三个账号暂时无数据
         */
        //$idAry = ["00K4RTVDJEHD53QA2S0909GM"];
        $idAry = $this->_getIds();
        // 数据量不大，直接一次性处理完
        $keyCount = count($idAry);
        foreach ($idAry as $key => $userId) {
            // 获取数据模型
            $fansList = UserFollowingRelationship::getModel($userId)
                ->where('user_id', $userId)
                ->where('attention_status', GlobalRelationshipConst::ATTENTION_STATUS_FANS)
                ->get()->toArray();
            $finish = count($fansList);
            foreach ($fansList as $index => $item) {
                $res = true;
                $data = [];
                // 查询是否已同步动态
                $dynamicList = SysDynamic::getModel($userId)
                    ->where('user_id', $userId)
                    ->where('is_deleted', GlobalConst::IS_NOT_DELETE)
                    ->get()->toArray();
                foreach ($dynamicList as $dynamic) {
                    $attention = UserAttention::getModel($item['follow_id'])
                        ->where('user_attention_id', $item['follow_id'])
                        ->where('user_id', $userId)
                        ->where('target_id', $dynamic['dynamic_id'])
                        ->where('is_deleted', GlobalConst::IS_NOT_DELETE)
                        ->first();
                    if (empty($attention)) {
                        $data[] = [
                            'user_attention_id' => $item['follow_id'],
                            'user_id' => $userId,
                            'target_id' => $dynamic['dynamic_id'],
                            'target_type' => GlobalConst::TARGET_TYPE_DYNAMIC,
                            'note_type' => $dynamic['note_type'],
                            'is_shield' => GlobalConst::IS_NOT_SHIELD,
                            'is_view' => $dynamic['is_view'],
                            'apply_at' => $dynamic['created_at'],
                            'dynamic_type' => $dynamic['type'],
                            'created_at' => $dynamic['created_at'],
                            'updated_at' => $dynamic['updated_at'],
                        ];
                    }
                }
                // 同步动态到粉丝关注列表
                if ($data) {
                    $res = UserAttention::getModel($item['follow_id'])->insert($data);
                    if ($res) {
                        $uid = UserAttention::getTableId($userId);
                        $fid = UserAttention::getTableId($item['follow_id']);
                        $info = "[$index/$finish][".($key+1)."/$keyCount] insert data to `user_attention_[$uid|$fid]` - " . json_encode($data);
                    } else {
                        $info = "[$index/$finish][".($key+1)."/$keyCount] insert failed : id - {$item['id']} uid - $userId - fid - " . $item['follow_id'];
                    }
                } else {
                    $info = "[$index/$finish][".($key+1)."/$keyCount] check data : id - {$item['id']} uid - $userId - fid - " . $item['follow_id'];
                }
                // log info
                $this->info($info);
                if ($data) $this->logger($info, false, 'script');
            }
        }
        return 1;
    }

    /**
     * get ids
     * @return array
     */
    private function _getIds()
    {
        $ids = $this->option('ids');
        $idAry = $ids ? explode(',', $ids) : [];
        return $idAry;
    }

}
